/**
 * sendLog之前需要 new jyrslog(业务id,渠道id,微信openid）注册日志基本信息，仅需注册一次
 * 然后调用sendLog(页面id)发送请求
 * @param {*} f1 系统id
 * @param {*} f2 渠道id
 * @param {*} openID 微信openID
 */
function jyrslog(f1,f2,openID) {
    this.systemID = f1
    this.sourceID = f2
    this.openID = openID
    this.id = checkCookie('id');
    this.pageID = null
    localStorage.setItem('jyrslog',JSON.stringify(this))
	this.sendLog = sendLog;
	this.sendErorrMsg = sendErorrMsg;
}
/**
 * 用于统计用户的浏览和页面简要处理时间的方法
 * @param {*} pageID 请求的页面id 
 */
function sendLog (pageID){

    if (!pageID) {
      throw new Error('页面ID不能为空')
    }
    if(!localStorage.getItem('jyrslog')) {
      throw new Error('发送日志前请先 new jyrslog(业务id,渠道id,微信openid)')
    }
    var jyrslog = JSON.parse(localStorage.getItem('jyrslog'))
    var timingObj = getTiming();
    if(!timingObj) {
        setTimeout(function() {
            sendLog(pageID);
        }, 200);
        return;
    }
	jyrslog.pageID = pageID;
    jyrslog.timingObj = timingObj;
    Util.post(jyrslog)

    // var url = jyrslog.url + '?systemID=' + jyrslog.systemID  + '&id=' + jyrslog.id + '&openid=' + jyrslog.openID + '&sourceID=' + jyrslog.sourceID + '&pageID=' + pageID + '&redirectTime=' + timingObj['redirectTime'] + '&dnsAnalysisTime=' + timingObj['dnsAnalysisTime']+ '&tcpHandShakeTime=' + timingObj['tcpHandShakeTime'] + '&httpRequestTime=' + timingObj['httpRequestTime'] + '&domBeforeLoadTime=' + timingObj['domBeforeLoadTime']+ '&domLoadTime=' + timingObj['domLoadTime'] + '&domAnalysisTime=' + timingObj['domAnalysisTime']+ '&scriptLoadTime=' + timingObj['scriptLoadTime'] + '&onloadTime=' + timingObj['onloadTime']+ '&pageLoadTime=' + timingObj['pageLoadTime']+ '&whiteScreenTime=' + timingObj['whiteScreenTime']
    // var script = document.createElement('script')
    // script.type = 'text/javascript'
    // script.src = url
    // document.body.appendChild(script)
}
/**
 * 用于统计用户操作业务逻辑错误的方法
 * @param {*} pageID 页面id
 * @param {*} errorMsg 业务逻辑错误信息
 */
function sendErorrMsg (pageID,errorMsg) {
    
    if (!pageID) {
      throw new Error('页面ID不能为空')
    }
    if(!localStorage.getItem('jyrslog')) {
      throw new Error('发送日志前请先 new jyrslog(业务id,渠道id,微信openid')
    }
    var jyrslog = JSON.parse(localStorage.getItem('jyrslog'))
    jyrslog.errorMsg = errorMsg;
    jyrslog.pageID = pageID;
    Util.post(jyrslog);
    // var jyrslog = JSON.parse(localStorage.getItem('jyrslog'))
    // var url = jyrslog.url + '?systemID=' + jyrslog.systemID  + '&id=' + jyrslog.id + '&openid=' + jyrslog.openID + '&sourceID=' + jyrslog.sourceID + '&pageID=' + pageID + 'errormsg=' + errorMsg
    // var script = document.createElement('script')
    // script.type = 'text/javascript'
    // script.src = url
    // document.body.appendChild(script)
}
/**
 * 用于统计用户点击按钮、单选框、多选框和超链接的数据的方法
 */
document.onclick = function(e) {
    if(e.target.type != 'button' && e.target.type != 'checkbox' && e.target.type != 'radio' && e.target.tagName != 'A'){
        return;
    }
    if(!localStorage.getItem('jyrslog')) {
      throw new Error('发送日志前请先 new jyrslog(业务id,渠道id,微信openid')
    }
    var jyrslog = JSON.parse(localStorage.getItem('jyrslog'))
    // var url = jyrslog.url + '?systemID=' + jyrslog.systemID  + '&id=' + jyrslog.id + '&openid=' + jyrslog.openID + '&sourceID=' + jyrslog.sourceID
    if(e.target.tagName == 'A') {
        // url += '&href=' +e.target.href;
        jyrslog.href = e.target.href;
    }else {
        jyrslog.type= e.target.type;
        jyrslog.name = e.target.name;
        jyrslog.value = e.target.value;
        // url += '&type=' + e.target.type + '&name=' + e.target.name + '&value=' + e.target.value
    }
    Util.post(jyrslog);
    // var script = document.createElement('script')
    // script.type = 'text/javascript'
    // script.src = url
    // document.body.appendChild(script)
}
/**
 * 用于统计用户点击下拉框的数据的方法
 */
document.onchange = function(e) {
    if(e.target.tagName != 'SELECT'){
        return;
    }
    if(!localStorage.getItem('jyrslog')) {
      throw new Error('发送日志前请先 new jyrslog(业务id,渠道id,微信openid')
    }
    var jyrslog = JSON.parse(localStorage.getItem('jyrslog'))
    jyrslog.type= 'select';
    jyrslog.name = e.target.name;
    jyrslog.value = e.target.value;
    Util.post(jyrslog);
    // var url = jyrslog.url + '?systemID=' + jyrslog.systemID  + '&id=' + jyrslog.id + '&openid=' + jyrslog.openID + '&sourceID=' + jyrslog.sourceID
    // url += '&type=select' + '&name=' + e.target.name + '&value=' + e.target.value
    // var script = document.createElement('script')
    // script.type = 'text/javascript'
    // script.src = url
    // document.body.appendChild(script)
}
/**
 * 用于统计ajax请求入参和返回的数据的方法
 */
var Util = {}

Util.extend = function extend() {
    var target = arguments[0] || {},
        i = 1,
        length = arguments.length,
        options, name, src, copy, clone

    if (length === 1) {
        target = this
        i = 0
    }

    for (; i < length; i++) {
        options = arguments[i]
        if (!options) continue

        for (name in options) {
            src = target[name]
            copy = options[name]

            if (target === copy) continue
            if (copy === undefined) continue

            if (Util.isArray(copy) || Util.isObject(copy)) {
                if (Util.isArray(copy)) clone = src && Util.isArray(src) ? src : []
                if (Util.isObject(copy)) clone = src && Util.isObject(src) ? src : {}

                target[name] = Util.extend(clone, copy)
            } else {
                target[name] = copy
            }
        }
    }

    return target
}
Util.isArray = function(arg) {
    return Object.prototype.toString.call(arg) === '[object Array]';
};

Util.isObject = function(arg) {
    return Object.prototype.toString.call(arg) === '[object Object]';
};

Util.post = function(data) {
    var xhr = new XMLHttpRequest();
    xhr.open('post',"https://localhost:8080");
    xhr.setRequestHeader('Content-Type','application/json')
    xhr.send(JSON.stringify(data))
}

/**
 * 用于存取cookie数据的方法
 * @param {*} cname cookie的字段名
 * @param {*} cvalue cookie的值
 * @param {*} cyear cookie的存储时效期
 */
function checkCookie(cname){
    var id=getCookie(cname);
    if (id!=""){
        return id;
    }
    else {
        var timestamp=Math.round(new Date().getTime()/1000);
        setCookie(cname,timestamp,'2138');
        return timestamp;
    }
}
function setCookie(cname,cvalue,cyear){
    var expires = new Date(cyear);
    document.cookie = cname+"="+cvalue+"; expires="+expires.toGMTString();
}
function getCookie(cname){
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i].trim();
        if (c.indexOf(name)==0) { 
            return c.substring(name.length,c.length);
        }
    }
    return "";
}

function objectToString(data){
    var astring = '';
    for(k in data){
        if(typeof data[k] === 'function') {
            astring += '';
        }else if(typeof data[k] === 'object') {
            astring += objectToString(data[k])
        }else {
            astring += '&' + k + '=' + data[k];
        }
    }
    return astring
}

function getTiming() {
        try {
            var time = performance.timing;
            var timingObj = {};

            //重定向时间
            timingObj['redirectTime'] = (time.redirectEnd - time.redirectStart) / 1000;
            //DNS解析时间
            timingObj['dnsAnalysisTime'] = (time.domainLookupEnd - time.domainLookupStart) / 1000;
            //TCP完成握手时间
            timingObj['tcpHandShakeTime'] = (time.connectEnd - time.connectStart) / 1000;
            //HTTP请求响应完成时间
            timingObj['httpRequestTime'] = (time.responseEnd - time.requestStart) / 1000;
            //DOM开始加载前所花费时间
            timingObj['domBeforeLoadTime'] = (time.responseEnd - time.navigationStart) / 1000;
            //DOM加载完成时间
            timingObj['domLoadTime'] = (time.domComplete - time.domLoading) / 1000;
            //DOM结构解析完成时间
            timingObj['domAnalysisTime'] = (time.domInteractive - time.domLoading) / 1000;
            //脚本加载时间
            timingObj['scriptLoadTime'] = (time.domContentLoadedEventEnd - time.domContentLoadedEventStart) / 1000;
            //onload事件时间
            timingObj['onloadTime'] = (time.loadEventEnd - time.loadEventStart) / 1000;
            //页面完全加载时间
            timingObj['pageLoadTime'] = (timingObj['redirectTime'] + timingObj['dnsAnalysisTime'] + timingObj['tcpHandShakeTime'] + timingObj['httpRequestTime'] + timingObj['domBeforeLoadTime'] + timingObj['domLoadTime']);
            //白屏时间
            timingObj['whiteScreenTime'] = (time.responseStart - time.navigationStart) / 1000;

            for(item in timingObj) {
                if(timingObj[item]<0){
                    return;
                }
                console.log(item + ":" + timingObj[item] + '毫秒(ms)');
            }
            return timingObj;
 
        } catch(e) {
            console.log(timingObj);
            console.log(performance.timing);
        }
}
